import re

from django.contrib.auth.backends import  ModelBackend

from users.models import User


class MeiDuoBack(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # check_password是一个对象函数filter获取的是查询集所以用get进行查询
        try:
            if re.match('^1[3-9]\d{9}$', username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except:
            return None

        else:#用户名与手机号正确，确认密码
            #check_password返回Ture/Flase 检查密码
               if user.check_password(password):
                   return user
               else:
                   return None


